#include "Config.h"
#include "FileSystem.h"
#include "StringEncoding.h"

#include <stdio.h>
#include <string>
#include <map>

std::string trim(const std::string& src, const std::string& what) {
	size_t i = src.find_first_not_of(what);
	if (i != std::string::npos) {
		size_t j = src.find_last_not_of(what);
		return src.substr(i, j - i + 1);
	}
	return std::string();
}

namespace Config {

	std::map<std::string, std::string> config;

	void loadConfig() {
		// default config
		config.clear();
		config["host"] = "127.0.0.1";
		config["port"] = "38443";
		config["root"] = "Z:\\";
		config["recursive"] = "1";
		config["key"] = "Hello world";
		config["iv"] = "Test only";

		std::wstring fn = getAppPath() + L"config.txt";
		FILE *f = _wfopen(fn.c_str(), L"rt");
		if (f == NULL) {
			printf("[WARNING] no config file found\n");
			f = _wfopen(fn.c_str(), L"wt");
			if (f) {
				for (auto it = config.begin(); it != config.end(); ++it) {
					fprintf(f, "%s=%s\n", it->first.c_str(), it->second.c_str());
				}
				fclose(f);
			}
		} else {
			printf("Config loaded\n");
			std::string s;
			while (myfgets(f, s) != NULL) {
				s = trim(s, " \t\r\n");
				if (!s.empty() && s[0] != '#') {
					size_t i = s.find_first_of('=');
					if (i != std::string::npos) {
						config[trim(s.substr(0, i), " \t\r\n")] = trim(s.substr(i + 1), " \t\r\n");
					}
				}
			}
			fclose(f);
		}

		for (auto it = config.begin(); it != config.end(); ++it) {
			printf("%s=%s\n", it->first.c_str(), it->second.c_str());
		}
	}

	std::string getConfig(const std::string& name) {
		if (config.empty()) loadConfig();
		auto it = config.find(name);
		return it == config.end() ? std::string() : it->second;
	}

	int getConfigAsInt(const std::string& name) {
		if (config.empty()) loadConfig();
		auto it = config.find(name);
		return it == config.end() ? 0 : atoi(it->second.c_str());
	}

}
